package servlet;

import com.alibaba.fastjson.JSON;
import until.BaseDao;
import until.BaseModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet(name = "AddNoticeServlet",urlPatterns = "/addnotice")
public class AddNoticeServlet extends HttpServlet {
    BaseDao baseDao = new BaseDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        req.setCharacterEncoding("utf-8");
        Object[] params = new Object[3];
        params[0]=req.getParameter("Title");
        params[1]=req.getParameter("Content");
        params[2]=new Date();
        String sql = "insert into t_notice(Title,Content,Time) values(?,?,?)";
        int result = baseDao.update(sql,params);
        BaseModel baseModel = new BaseModel();
        if(result>0){
            baseModel.setCode(1);
            baseModel.setMessage("新增"+result+"条公告成功");
        }else{
            baseModel.setCode(-1);
            baseModel.setMessage("新增公告失败");
        }
        String baseModelStr = JSON.toJSONString(baseModel);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(baseModelStr);
        resp.getWriter().flush();
        resp.getWriter().close();
    }
}
